<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class CateController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //分类列表页
        //查询数据
        $data = DB::table('cate as c1')
        -> leftjoin('cate as c2', 'c1.pid', '=', 'c2.id') 
        -> select('c1.*','c2.name as parentName',DB::raw("CONCAT(c1.path,',',c1.id) as sortPath"))
        -> where('c1.name', 'like', '%'.$request -> input('keywords').'%' )    
        -> orderby('sortPath')
        ->paginate($request -> input('num', 10));//每页显示条数
        //遍历分类
        foreach ($data as $k => $v) {
            $num = substr_count($v -> path, ',');
            $data[$k] -> name = str_repeat('|---', $num).$v -> name;
            if($data[$k] -> parentName == '')
            {
                $data[$k] -> parentName = '根分类';
            }
        }
        return view('admin.cate.index', ['data' => $data, 'request' => $request -> all()]);
        return view('admin.cate.menucate', ['data' => $data, 'request' => $request -> all()]);
        
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //添加分类表单
        //查询
        //SELECT *,CONCAT(path,',',id) as sortPath from cate ORDER BY sortPath
        $data = DB::table('cate') 
        -> select('*',DB::raw("CONCAT(path,',',id) as sortPath"))
        -> orderby('sortPath')
        -> get();
        //遍历分类
        foreach ($data as $k => $v) {
            $num = substr_count($v -> path, ',');
            $data[$k] -> name = str_repeat('|---', $num).$v -> name;
        }
        return view('admin.cate.add', ['data' => $data]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //执行添加
        $data = $request -> except('_token');
        // dd($data);
        if($data['pid'] == 0)
        {
            $path = 0;
        }else
        {
            $parentPath = DB::table('cate') -> where('id', $data['pid']) -> first() -> path;
             // dd($parentPath);
            //拼接path
            $path = $parentPath.','.$data['pid'];
            $data['path'] = $path;
        }

        //上传图片
        if($request -> hasFile('headimg'))
        {
            if($request -> file('headimg') -> isValid())
            {
                //移动文件
                $suffix = $request -> file('headimg') -> getClientOriginalExtension();
                //随机一个文件名
                $filename = time().mt_rand(100000,9999999);

                //移动文件
                $request -> file('headimg') -> move('./uploads', $filename.'.'.$suffix);
                $data['headimg'] = $filename.'.'.$suffix;
            }

        }
        
        // dd($data);
       $res= DB::table('cate') -> insert($data,$path);
       if($res)
       {
            return redirect('/admin/cate') -> with(['info' => '添加分类成功']);
       }else
       {
            return back() -> with(['info' => '添加分类失败']);
       }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //修改分类
        // 查询数据
        $data = DB::table('cate') -> where('id', $id) ->first();
        $allData = DB::table('cate') 
        -> select('*',DB::raw("CONCAT(path,',',id) as sortPath"))
        -> orderby('sortPath')
        -> get();
        //遍历分类
        foreach ($allData as $k => $v) {
            $num = substr_count($v -> path, ',');
            $allData[$k] -> name = str_repeat('|---', $num).$v -> name;
        }      
        return view('admin.cate.edit', ['data' => $data, 'allData' => $allData]);
         
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        //执行添加
        $data = $request -> except('_token', '_method'); 

        if(empty($data['nav_position']))
        {
            $data['nav_position']='0';
        }
         if(empty($data['menu_position']))
        {
            $data['menu_position']='0';
        }
        if($data['pid'] == 0)
        {
            $path = 0;
        }else
        {
            $parentPath = DB::table('cate') -> where('id', $data['pid']) -> first() -> path;
             // dd($parentPath);
            //拼接path
            $path = $parentPath.','.$data['pid'];
            $data['path'] = $path;
        }

        //上传图片
        if($request -> hasFile('headimg'))
        {
            if($request -> file('headimg') -> isValid())
            {
                //移动文件
                $suffix = $request -> file('headimg') -> getClientOriginalExtension();
                //随机一个文件名
                $filename = time().mt_rand(100000,9999999);

                //移动文件
                $request -> file('headimg') -> move('./uploads', $filename.'.'.$suffix);
                $data['headimg'] = $filename.'.'.$suffix;
            }

        }
        //执行更新
        $res = DB::table('cate') -> where('id', $id) -> update($data);
        //判断
         if($res)
       {
            return redirect('/admin/cate') -> with(['info' => '修改分类成功']);
       }else
       {
            return back() -> with(['info' => '修改分类失败']);
       }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // 判断是否有子分类
        $r = DB::table('cate') -> where('pid', $id) -> first();
        if($r)
        {
            return redirect('/admin/cate') -> with(['info' => '有子分类,无法删除']);
        } 

        //删除分类
        $res = DB::table('cate') -> where('id', $id) -> delete();
        //判断
         if($res)
       {
            return redirect('/admin/cate') -> with(['info' => '删除分类成功']);
       }else
       {
            return back() -> with(['info' => '删除分类失败']);
       }
    }

    

}
